/* 04-join.c

   Simple illustration of dividing work among two threads

   pthread.h should be first otherwise compile with -D_THREAD_SAFE 
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct {
   int *ar;
   long n;
   int id;
   int sum;
} subarray;


void *incer(void *arg) {
   long i;
   int id = ((subarray*)arg)->id;

   printf("Start thread: %d sum=%ld\n",id, ((subarray*)arg)->sum);
   for (i = 0; i < ((subarray*)arg)->n; i++) {
      ((subarray*)arg)->ar[i]++;
      ((subarray*)arg)->sum++;
   }
   printf("Terminating thread: %d sum=%ld\n",id, ((subarray*)arg)->sum);
   pthread_exit(NULL);
}

int main() {
   int ar[1000000];
   pthread_t th1, th2;
   subarray sb1, sb2;

   sb1.ar = &ar[0];
   sb1.n  = 500000;
   sb1.id = 1;
   sb1.sum = 0;
   pthread_create(&th1, NULL, incer, &sb1);

   sb2.ar = &ar[500000];
   sb2.n  = 500000;
   sb2.id = 2;
   sb2.sum = 0;
   pthread_create(&th2, NULL, incer, &sb2);

   pthread_join(th1, NULL);
   pthread_join(th2, NULL);
   printf("Terminating main: %d sum=%d\n",getpid(),sb1.sum+sb2.sum);
   pthread_exit(NULL);
   return 0;
}
